<style scoped lang="scss">

</style>

<template>
  <div class="CascaderSelector-wrap">
    <van-popup v-model="showModal" round position="bottom">
      <template v-if="options && options.length">
        <van-cascader
            v-model="cascaderValue"
            :title="title"
            :options="options"
            @close="showModal = false"
            @change="onChange"
            @finish="onFinish"
        />
      </template>
    </van-popup>
  </div>
</template>

<script>
  export default {
    name: 'CascaderSelector',
    components: {},
    props: {
      title: {
        type: String,
        default: '请选择城市'
      },
      keyName: {
        type: String,
        default: null
      }
    },
    data() {
      return {
        showModal: false,
        cascaderValue: '',
        options: []
      }
    },
    methods: {
      show(data) {
        this.showModal = true;
        this.options = data;
      },
      getDatas(id, data) {
        // console.log(id, data)
        // 根据id找到对应的children 然后塞进去
        this.options.map(k => {
          return this.getItems(id, data, k)
        })
        // console.log(this.options)
      },
      getItems(id, data, source) {
        if(source.value === id) {
          source.children = data;
          return source
        }

        if(source.children && source.children.length) {
          return source.children.map(k => {
            if(k.value === id) {
              k.children = data;
              return k;
            } else {
              if(k.children && k.children.length) {
                k.children = this.getItems(id, data, k.children)
              }
            }
          })
        }
      },
      hide() {
        setTimeout(() => {
          this.cascaderValue = '';
          this.options = [];
        }, 500)
      },
      onChange(e) {
        this.$emit('on-change',
          {
            level: e.tabIndex,
            value: e.value
          }
        )
      },
      onFinish(e) {
        this.showModal = false;
        this.$emit('on-finish', e.selectedOptions)
      }
    },
    computed: {},
    watch: {
      showModal(n) {
        if(!n) {
          this.hide();
        }
      }
    }
  }
</script>
